from django.shortcuts import render
from django.http import HttpRequest, HttpResponse, JsonResponse
import time
import simplejson
from .models import Result
from django.db import transaction


def input_results(request: HttpRequest):
    print(request.body)
    try:
        for result in simplejson.loads(request.body).get("results"):
            # 先看学号是否已经存在,存在则覆盖
            with transaction.atomic():
                obj = Result.objects.filter(stu_id=result.get("stu_id")).first()
                if obj:
                    obj.chinese = result.get("chinese")
                    obj.math = result.get("math")
                    obj.english = result.get("english")
                else:
                    obj = Result(stu_id=result.get("stu_id"), chinese=result.get("chinese"), math=result.get("math"),
                             english=result.get("english"))
                obj.save()
    except Exception as e:
        return HttpResponse(status=400)

    return HttpResponse(status=200)


def query_result(request: HttpRequest):
    try:
        stu_id = int(simplejson.loads(request.body).get("stu_id", 0))
        if stu_id:
            obj = Result.objects.filter(stu_id=stu_id).first()
            if obj:
                data = {"stu_id": obj.stu_id, "chinese": obj.chinese, "math": obj.math, "english": obj.english}
                print(data)
                return JsonResponse(data)
            else:
                return HttpResponse(status=402)
    except:
        return HttpResponse(status=400)


def check_role(request: HttpRequest):
    session = request.session
    if session.get("role") == "teacher":
        time.sleep(3)
        return HttpResponse(status=200)
    elif session.get("role") == "student":
        return HttpResponse(status=400)
    else:
        return HttpResponse(status=401)

